<template>
  <div class="tinymce-editor">
    <Editor
        api-key="ycamu6hikog3ki66tibtyujs8o56b0rlvryh5aqzf3y82max"
        v-model="content"
        :init="init"
        :disabled="disabled"
        @onInit="handleInit"
    />
  </div>
</template>

<script setup>
import Editor from '@tinymce/tinymce-vue'
import { ref, watch } from 'vue'
import { uploadOSS } from '@/api/upload'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  height: {
    type: [Number, String],
    default: 500
  }
})

const emit = defineEmits(['update:modelValue', 'change'])
const content = ref(props.modelValue)
const editorRef = ref(null)

// TinyMCE 配置
const init = {
  language: 'zh_CN',
  height: props.height,
  menubar: true,
  plugins: [
    'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
    'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
    'insertdatetime', 'media', 'table', 'help', 'wordcount'
  ],
  toolbar: 'undo redo | formatselect | ' +
      'bold italic backcolor | alignleft aligncenter ' +
      'alignright alignjustify | bullist numlist outdent indent | ' +
      'removeformat | image | code | help',
  content_style: `
    body { font-family: -apple-system, BlinkMacSystemFont, San Francisco, Segoe UI, Roboto, Helvetica Neue, sans-serif; }
    .article-container { max-width: 100%; margin: 0 auto; }
    .article-lead { margin-bottom: 2em; }
    .lead-paragraph { font-size: 1.1em; line-height: 1.6; margin-bottom: 1em; }
    .article-image { margin: 2em 0; text-align: center; }
    .article-image img { max-width: 100%; height: auto; }
    .section-heading { font-size: 1.5em; margin: 1.5em 0 1em; }
    .article-section { margin: 2em 0; }
    .article-paragraph { margin: 1em 0; line-height: 1.6; }
  `,
  content_css: false,
  image_advtab: true,
  image_uploadtab: true,
  images_upload_handler: async (blobInfo, progress) => {
    try {
      const formData = new FormData()
      formData.append('file', blobInfo.blob())

      const { data } = await uploadOSS(formData)

      if (data && data.url) {
        return data.url
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('上传失败:', error)
      ElMessage.error('图片上传失败')
      throw new Error('上传失败')
    }
  },
  setup: function(editor) {
    editor.on('init', function() {
      editor.getBody().style.fontSize = '16px'
    })
  }
}

// 监听内容变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== content.value) {
    content.value = newValue
  }
})

watch(content, (newValue) => {
  emit('update:modelValue', newValue)
  emit('change', newValue)
})

const handleInit = (editor) => {
  editorRef.value = editor
}
</script>

<style>
.tinymce-editor {
  position: relative;
  line-height: normal;
}
</style>